package gluehttp

import (
	"errors"
	"github.com/gin-gonic/gin"
	v1 "gluenet/pkg/log/v1"
)

const (
	SuccessCode     = 200
	successMessage  = "Success"
	GlabalErrorCode = "E50000"
	GlobalError     = "global_error"
	TranceIdKey     = "tranceId"
	ParamErrorCode  = "E10000"
	ParamError      = "请求参数错误"
)

func Response(c *gin.Context, data interface{}) {
	c.JSON(200, newSuccessResponseData(c.GetString(TranceIdKey), data))
}

func ErrorResponse(c *gin.Context, err ResponseError) {
	if err.Err == nil {
		err.Err = errors.New(err.Message)
		v1.Warnf("err in ResponseError is nil")
	}
	c.JSON(900, newResponseData(c.GetString(TranceIdKey), err.Code, err.Message, err.Err.Error(), nil))
}

type ResponseData struct {
	TranceId string      `json:"tranceId"`
	Code     int         `json:"code"`
	Message  string      `json:"msg"`   // 用户提示信息
	Error    string      `json:"error"` // 开发信息
	Data     interface{} `json:"data"`  // 必须是object类型
}

func newSuccessResponseData(tranceId string, data interface{}) *ResponseData {
	return newResponseData(tranceId, SuccessCode, successMessage, "", data)
}

func newResponseData(tranceId string, code int, message, errorMessage string, data interface{}) *ResponseData {
	return &ResponseData{
		TranceId: tranceId,
		Code:     code,
		Message:  message,
		Error:    errorMessage,
		Data:     data,
	}
}
